/**业务管理流程平台版本1.0,生成时间:2017-04-13 13:16:48**/
package com.xbdun.service.bmp.biz.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.xbdun.common.enums.PkGenerateEnum;
import com.xbdun.common.page.Pager;
import com.xbdun.common.util.PkGenerator;
import com.xbdun.common.validate.ValidateUtil;
import com.xbdun.dao.bmp.entity.XbdunSysUserDo;
import com.xbdun.dao.bmp.entity.XbdunSysUserMobilesDto;
import com.xbdun.dao.bmp.mapper.SysUserMapper;
import com.xbdun.dao.bmp.mapper.SysUserMobilesMapper;
import com.xbdun.facade.bmp.exceptions.BmpBizException;
import com.xbdun.facade.bmp.response.system.SysUserResponse;
import com.xbdun.service.bmp.biz.SysUserBiz;


/**
 * 平台用户信息
 * @ClassName XbdunSysUserServiceImpl
 * @author 张国涛
 * @2017-04-13 13:16:48
 */
@Service
@Transactional
public class SysUserBizImpl implements SysUserBiz {
	@Autowired
	private SysUserMapper sysUserMapper;
	
	@Autowired
	SysUserMobilesMapper sysUserMobilesMapper;
	
	Log log = LogFactory.getLog(SysUserBizImpl.class);

	/**
	 * 根据主键获取对象
	 * @return {@link XbdunSysUserDo}
	 */
	public XbdunSysUserDo getByUserCode(long userCode)throws RuntimeException{
		Assert.isTrue(userCode>0, "主键userCode不能小于零");
		
		return sysUserMapper.getByUserCode(userCode);
	}
	
	/**
	* @Title: getByIdCard
	* @Description: 根据身份证获取用户编号
	* @param idCard	身份证号
	* @return Long    返回类型
	 */
	public Long getByIdCard(String idCard)throws RuntimeException{
		return sysUserMapper.getByIdCard(idCard);
	}
	/**
	 * 新增
	 * @param xbdunSysUserDo 
	 */
	public Long addXbdunSysUser(XbdunSysUserDo xbdunSysUserDo)throws RuntimeException{
		Assert.notNull(xbdunSysUserDo,"新增xbdunSysUserDo对象不能为Null");
		
		return sysUserMapper.addXbdunSysUser(xbdunSysUserDo);
	}
	
	/**
	* @Title: existUnionId
	* @Description: 判断微信小程序的UnionId是否已经存在
	* @param unionId 用户的唯一值
	* @return boolean    返回类型
	 */
	public boolean existUnionId(String unionId){
		Assert.isTrue(StringUtils.isNotBlank(unionId), "小程序唯一Id不能为空");
		return sysUserMapper.existUnionId(unionId)>0;
	}
	
	/**
	 * 删除数据根据主键
	 * @param userCode
	 */
	public void delByUserCode(long userCode)throws RuntimeException{
		Assert.isTrue(userCode>0, "主键userCode不能小于零");
		
		sysUserMapper.delByUserCode(userCode);
	}
	
	/**
	 * 判断是否存在,不为null则是存在
	 * @param id 主键id
	 * @return Long
	 */
	public boolean existById(long id)throws RuntimeException{
		Assert.isTrue(id>0,"参数id必须大于零");
		Map<String,Object> param = new HashMap<String, Object>();
		
		//根据主键
		param.put("id",id);
		
		Long rlt = sysUserMapper.existXbdunSysUser(param);

		param.clear();
		param = null;

		return (null==rlt||rlt.longValue()==0?false:true);
	}
	
	/**
	 * 更新对象属性
	 * @param XbdunSysUserDo	更新对象
	 * @param userCode
	 */
	public void updateById(XbdunSysUserDo xbdunSysUserDo,long userCode)throws RuntimeException{
		
		Assert.isTrue(null!=xbdunSysUserDo,"更新xbdunSysUserDo对象不能为空");
		
		Map<String,Object> param = new HashMap<String,Object>();
		//TODO 自定义更新对象属性 
		/**
		 param.put("userCode", xbdunSysUserDo.getUserCode());
		 param.put("userName", xbdunSysUserDo.getUserName());
		 param.put("pwd", xbdunSysUserDo.getPwd());
		 param.put("sex", xbdunSysUserDo.getSex());
		 param.put("email", xbdunSysUserDo.getEmail());
		 param.put("mobile", xbdunSysUserDo.getMobile());
		 param.put("realName", xbdunSysUserDo.getRealName());
		 param.put("birthDate", xbdunSysUserDo.getBirthDate());
		 param.put("type", xbdunSysUserDo.getType());
		 param.put("qqOpenid", xbdunSysUserDo.getQqOpenid());
		 param.put("qq", xbdunSysUserDo.getQq());
		 param.put("createTime", xbdunSysUserDo.getCreateTime());
		 param.put("version", xbdunSysUserDo.getVersion());
		 param.put("orgCode", xbdunSysUserDo.getOrgCode());
		 param.put("refNo", xbdunSysUserDo.getRefNo());
		 param.put("refUserCode", xbdunSysUserDo.getRefUserCode());
		 param.put("refRank", xbdunSysUserDo.getRefRank());
		 param.put("idCard", xbdunSysUserDo.getIdCard());

		 * 属性对应的Map的键-值
		 */
		Map<String,Object> where = new HashMap<String,Object>();
		
		where.put("userCode", userCode);
		
		sysUserMapper.updateDynXbdunSysUser(param, where);

		param.clear();
		where.clear();
		param = null;
		where = null;
	}
	
	/**
	 * 查询分页
	 * @param where			约束条件,键是对象属性其中条件都为and连接
	 * @param orderBy		排序条件
	 * @param pageNum   	当前索引页
	 * @param numPerPage	每页显示条数
	 * @return
	 * @throws RuntimeException
	 */
	public Pager<XbdunSysUserDo> queryPager(Map<String,Object> where,String orderBy,int pageIndex,int pageSize){
		log.info(where);
		//分页对象
		Pager<XbdunSysUserDo> resultPager = new Pager<XbdunSysUserDo>();
		
		resultPager.setPageSize(pageSize);
		resultPager.setPageIndex(pageIndex);
		resultPager.setSort(orderBy);
		
		Long resultCnt = sysUserMapper.queryPagerCount(where);
		if(null!=resultCnt&&resultCnt.longValue()==0){
			
			resultPager.setTotalCount(0);
			return resultPager;
		}
		
		//获取查询结果集List
		List<XbdunSysUserDo> list = sysUserMapper.queryPager(where, orderBy,(resultPager.getPageIndex()-1)*resultPager.getPageSize(), resultPager.getPageSize());
		
		//设置查询条数
		resultPager.setTotalCount(resultCnt.longValue());
		resultPager.setPager();
		resultPager.setData(list);
		
		return resultPager;
	}

	public XbdunSysUserDo getSysUserOrCreate(XbdunSysUserDo xbdunSysUserDo, String mobile) throws RuntimeException {
		Long userMobileId = null;
		XbdunSysUserDo dbSysDto = null;    //数据库存在对象
		Map<String,Object> param = new HashMap<String,Object>();   //更新对象
		if(xbdunSysUserDo.getUserCode()>0){
			dbSysDto = sysUserMapper.getByUserCode(xbdunSysUserDo.getUserCode());
		}
		//根据微信UnionId查询用户
		if(null==dbSysDto&&StringUtils.isNotBlank(xbdunSysUserDo.getUnionid())){
			//通过微信UnionId获取用户
			dbSysDto = sysUserMapper.getByUnionId(xbdunSysUserDo.getUnionid());
		}
		//根据身份证查询
		if(null==dbSysDto&&ValidateUtil.isIdCard(xbdunSysUserDo.getIdCard())){
			//通过微信UnionId获取用户
			dbSysDto = sysUserMapper.getByUserIdCard(xbdunSysUserDo.getIdCard());
		}
		if(null!=dbSysDto){
			//创建用户
			if(StringUtils.isNotBlank(xbdunSysUserDo.getUnionid())){
				if(StringUtils.isNotBlank(dbSysDto.getUnionid())){
					//判断数据库的用户UnionId与传入的unionId是否相同
					if(!dbSysDto.getUnionid().equals(xbdunSysUserDo.getUnionid())){
						throw BmpBizException.WX_UNION_ID_NO;
					}
				}else{
					//微信小程序的UnionId
					param.put("unionid", xbdunSysUserDo.getUnionid());
					param.put("xcxOpenId", xbdunSysUserDo.getQqOpenid());
				}
			}
			//判断身份证是否正确
			if(ValidateUtil.isIdCard(xbdunSysUserDo.getIdCard())){
				if(StringUtils.isNotBlank(dbSysDto.getIdCard())){
					if(!dbSysDto.getIdCard().equals(xbdunSysUserDo.getIdCard())){
						throw BmpBizException.ID_CARD_NO;
					}
				}else{
					//微信小程序的UnionId
					param.put("idCard",xbdunSysUserDo.getIdCard());
				}
			}
			
			//需要动态的更新用户信息
			if(param.size()>0){
				Map<String,Object> _where = new HashMap<String,Object>();
				_where.put("userCode", dbSysDto.getUserCode());
				_where.put("version", dbSysDto.getVersion());
				if(0==sysUserMapper.updateDynXbdunSysUser(param, _where)){
					throw BmpBizException.DB_UPDATE_RESULT_0.newInstance("更新用户基本信息失败，系统繁忙请稍后...");
				}
			}
			
			//判断用户电话是否存在
			if(StringUtils.isNotBlank(mobile)){
				if(sysUserMobilesMapper.existUserMobile(xbdunSysUserDo.getUserCode(), mobile)==0){
					XbdunSysUserMobilesDto model = new XbdunSysUserMobilesDto();
					userMobileId = PkGenerator.generateLongPk(PkGenerateEnum.SYSFRAME);
					model.setId(userMobileId);
					model.setMobile(mobile);
					model.setUserCode(xbdunSysUserDo.getUserCode());
					sysUserMobilesMapper.insertUserMobile(model);
				}
			}
		}else{
			//不存在那么就需要新增用户信息
			if(xbdunSysUserDo.getUserCode()<=0) {
				xbdunSysUserDo.setUserCode(PkGenerator.generateLongPk(PkGenerateEnum.SYSFRAME));
			}
			Long addXbdunSysUser = sysUserMapper.addXbdunSysUser(xbdunSysUserDo);
			if(null == addXbdunSysUser||addXbdunSysUser.longValue()==0){
				throw BmpBizException.DB_INSERT_RESULT_0.newInstance("新增用户失败");
			}
			
			//判断用户是否已经存在电话号码
			if(ValidateUtil.isMobile(mobile)){
				XbdunSysUserMobilesDto model = new XbdunSysUserMobilesDto();
				userMobileId = PkGenerator.generateLongPk(PkGenerateEnum.SYSFRAME);
				model.setId(userMobileId);
				model.setMobile(mobile);
				model.setUserCode(xbdunSysUserDo.getUserCode());
				sysUserMobilesMapper.insertUserMobile(model);
			}
		}
		//判断获取用户基本信息
		return (null!=dbSysDto?dbSysDto:xbdunSysUserDo);
	}

	public SysUserResponse getSysUserLogin(XbdunSysUserDo xbdunSysUserDo) throws Exception {
		SysUserResponse response = null;
		XbdunSysUserDo dbSysDto = null;
		//默认密码为身份证后六位
		if(xbdunSysUserDo.getUserCode()>0){
			dbSysDto = sysUserMapper.getByUserCode(xbdunSysUserDo.getUserCode());
		}
		//根据微信UnionId查询用户
		if(null==dbSysDto&&StringUtils.isNotBlank(xbdunSysUserDo.getUnionid())){
			//通过微信UnionId获取用户
			dbSysDto = sysUserMapper.getByUnionId(xbdunSysUserDo.getUnionid());
		}
		//根据身份证查询
		if(null==dbSysDto&&ValidateUtil.isIdCard(xbdunSysUserDo.getIdCard())){
			//通过微信UnionId获取用户
			dbSysDto = sysUserMapper.getByUserIdCard(xbdunSysUserDo.getIdCard());
		}
		if(null != dbSysDto){
			response = new SysUserResponse();
			response.setUnionid(dbSysDto.getUnionid());
			response.setUserCode(dbSysDto.getUserCode());
			response.setRealName(dbSysDto.getRealName());
			response.setSex(dbSysDto.getSex());
			response.setUserName(dbSysDto.getUserName());
			response.setImgUrl(dbSysDto.getImgUrl());
			//判断是否归属机构总数
			response.setToOrgCnt(sysUserMapper.getToOrgCnt(dbSysDto.getUserCode()));
			dbSysDto = null;
		}
		return response;
	}

	public Long getUserCodeByUnion(String unionId) throws RuntimeException {
		return sysUserMapper.getUserCodeByUnion(unionId);
	}

	public int updateUserByInvite(long userCode, String unionId, String openId, BigDecimal latitude,BigDecimal longitude) {
		return sysUserMapper.updateUserByInvite(userCode,unionId,openId,latitude,longitude);
	}

}